<template>
  <div>
    <a-card :bordered="false" style="margin-bottom: 10px;padding-bottom: 10px">
      <!-- 步骤引导 -->
      <div class="table-page-search-wrapper" ref="search">
        <a-steps :current="currentStep">
          <a-step>
            <!-- <span slot="title">Finished</span> -->
            <template #title>读取信息</template>
            <template #description>
              <span>扫码或录入学号以查询</span>
            </template>
          </a-step>
          <a-step title="校验与分配" description="校验是否允许分配" />
          <a-step title="完成分配" description="完成分配与结果展示" />
        </a-steps>
      </div>
    </a-card>

    <a-card :bordered="false" class="table-card">
      <div v-show="currentStep==0">
        <!--    扫码读取    -->
        <a-result
          :status="conStatus?'success':'error'"
          :title="conStatus?'已连接至Now云服务':'未连接至Now云服务'"
          :sub-title="conStatus?'已连接至云服务，可使用 理想MMS 终端进行扫码':'未连接至云服务，可使用手动录入或检查网络'"
        >
          <template #extra>
            <div style="width: 70%">
              <a-input
                style="margin-left: 20%"
                v-model="userId"
                size="large"
                placeholder="手动输入快速身份识别码"
              />
            </div>
            <div style="text-align: center;margin-top: 2%">
              <a-button key="console" type="primary" @click="distributionLogFun">校 验</a-button>
              <a-button key="buy" style="margin-left: 2%">重 置</a-button>
            </div>
          </template>
        </a-result></div>
      <div v-show="currentStep==1">
        <div style="padding:3%">
          <a-card :bordered="false">
            <div style="float: right">
              <a-button size="default" type="primary" :disabled="userId==undefined" @click="selectDormShow=true">分配</a-button>
              <a-button :disabled="userId==undefined" @click="backBtnTipShow=true">回撤</a-button>
            </div>
            <a-descriptions title="基础信息">
              <a-descriptions-item label="用户标识">{{ userInfo.id }}</a-descriptions-item>
              <a-descriptions-item label="姓名">{{ userInfo.name }}</a-descriptions-item>
              <a-descriptions-item label="学号">{{ userInfo.no }}</a-descriptions-item>
              <a-descriptions-item label="性别">{{ userInfo.sex==0?'男':'女' }}</a-descriptions-item>
              <a-descriptions-item label="类型">{{ userInfo.userType==0?'前台用户':'后台用户' }}</a-descriptions-item>
              <a-descriptions-item label="手机">{{ userInfo.phonenumber }}</a-descriptions-item>
            </a-descriptions>
            <a-divider style="margin-bottom: 32px"/>
            <a-descriptions title="班级信息" v-if="userInfo.sysDept">
              <a-descriptions-item label="名称">{{ userInfo.sysDept.deptName }}</a-descriptions-item>
              <a-descriptions-item label="负责人">{{ userInfo.sysDept.leader }}</a-descriptions-item>
            </a-descriptions>
            <a-divider style="margin-bottom: 32px"/>

            <div class="title">分配日志</div>
            <a-table :dataSource="dormLogs" :columns="logColumns" rowKey="id">
              <template slot="status" slot-scope="record">
                <a-tag color="#87d068" v-if="record==0">正常</a-tag>
                <a-tag color="#f50" v-else>转出</a-tag>
              </template>
            </a-table>
          </a-card>
        </div>
      </div>
      <div v-show="currentStep==2">
        <a-result :title="distributionResultTip" status="success">
          <template #extra>
            <a-button type="primary" @click="$router.go(0)">继续操作</a-button>
          </template>
        </a-result>
      </div>
    </a-card>
    <a-modal :visible="backBtnTipShow" title="回撤操作" @ok="backBtnFun" @cancel="backBtnTipShow=false">
      <p>1、回撤操作会将用户移出所在宿舍，标记为未分配宿舍，同时会产生一条宿舍异动记录</p>
      <p>2、如果不存在宿舍分配记录，回撤操作将不会被执行</p>
      <p>3、建议回撤操作完成后需要点击分配按钮重新分配宿舍</p>
      <p>4、点击取消按钮，将<b>不会</b>执行回撤操作</p>
      <p>5、点击确定按钮，将<b style="color:red">立即</b>执行回撤操作</p>
    </a-modal>
    <a-modal :visible="selectDormShow" title="选择公寓" @ok="distributionFun" @cancel="selectDormShow=false;buildObject=undefined">
      <select-dorm
        v-model="buildObject"
        select-model="single"
        :select-scope="selectScope"
        @callBack="onSelectDorm"
      />
    </a-modal>
  </div>
</template>

<script>
import allIcon from '@/core/icons'
import { distribution, distributionLog, dormBack } from '@/api/modules/ModDormUser'
import AdvanceTable from '@/components/pt/table/AdvanceTable'
import selectDorm from '@/components/pt/selectDorm/SelectDorm'
import { mapGetters } from 'vuex'

export default {
  name: 'Dorm',
  components: {
    selectDorm,
    AdvanceTable,
    allIcon
  },
  data () {
    return {
      currentUID: undefined,
      currentStep: 0,
      selectDormShow: false,
      backBtnTipShow: false,
      maxRetry: 3,
      currentRetry: 0,
      conStatus: false,
      userId: undefined,
      buildObject: undefined,
      userInfo: {},
      dormLogs: [],
      distributionResultTip: '',
      selectScope: 'room',
      logColumns: [
        {
          title: '流水号',
          dataIndex: 'id',
          key: 'id'
        }, {
          title: '房间号',
          dataIndex: 'buildName',
          key: 'buildName'
        }, {
          title: '开始时间',
          dataIndex: 'createTime',
          key: 'createTime'
        }, {
          title: '结束时间',
          dataIndex: 'updateTime',
          key: 'updateTime'
        }, {
          title: '居住状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' },
          key: 'status'
        }
      ]
    }
  },
  filters: {
  },
  mounted() {
    // 创建websocket连接
    this.currentUID = this.uid
    console.log(this.currentUID)
    this.initWebSocket('wss://vimdas.tianguishan.com.cn/socket/wsPushMessage/W' + this.uid)
    // this.initWebSocket('ws://vimdas.tianguishan.com.cn/api/wsPushMessage/W' + this.uid)
  },
  created () {
  },
  computed: {
    ...mapGetters({ uid: 'uid' })
  },
  watch: {
  },
  methods: {
    // 分配公寓
    distributionFun() {
      if (this.buildObject === undefined || this.buildObject == null) {
        this.$message.warning('请选择房间后进行分配')
        return false
      }
      if (this.checkUserIdFun()) {
        distribution(this.buildObject.ids, this.userId).then(res => {
          this.distributionResultTip = res.msg
          // this.distributionLogFun()
          this.buildObject = undefined
          this.userId = undefined
          // this.userInfo = undefined
          this.dormLogs = []
          this.selectDormShow = false
          this.currentStep = 2
        })
      }
    },
    // 选择公寓结束回调
    onSelectDorm(e) {

    },
    checkUserIdFun() {
      if (this.userId === undefined) {
        this.$message.error('错误N022，用户标识不合法')
        return false
      }
      this.userId = this.userId.replace(/[\u4e00-\u9fa5/\s+/]|[^a-zA-Z0-9\u4E00-\u9FA5]/g, '')
      if (this.userId === undefined || this.userId === '') {
        this.$message.error('错误N022，用户标识不合法')
        return false
      }
      return true
    },
    backBtnFun() {
      if (this.checkUserIdFun()) {
        dormBack(this.userId).then(res => {
          this.$message.success('回撤成功，请及时重新分配')
          this.distributionLogFun()
          this.backBtnTipShow = false
        })
      }
    },
    distributionLogFun() {
      if (this.checkUserIdFun()) {
        distributionLog(this.userId).then(res => {
          if (res.data.user == null) {
            this.$message.error('错误N022，用户标识不合法')
            return false
          }
          this.userInfo = res.data.user
          this.dormLogs = res.data.dorm
          this.currentStep = 1
        })
      }
    },
    // 初始化weosocket
    initWebSocket(wsuri) {
      if (typeof WebSocket === 'undefined') {
        return console.log('您的浏览器不支持websocket')
      }
      this.websock = new WebSocket(wsuri)
      this.websock.onmessage = this.websocketonmessage
      this.websock.onopen = this.websocketonopen
      this.websock.onerror = this.websocketonerror
      this.websock.onclose = this.websocketclose
    },
    websocketonopen() {
      // 连接建立之后执行send方法发送数据
      // const actions = { message: 'nowasHeartbeat' }
      this.websocketsend('nowasHeartbeat')
      // 设置链接状态为正常
      this.conStatus = true
    },
    websocketonerror() {
      // 连接建立失败重连
      console.log('失败重连')
      const that = this
      setTimeout(function() {
        if (that.currentRetry <= that.maxRetry) {
          that.currentRetry++
          that.initWebSocket()
        }
      }, 5000 * that.currentRetry)
    },
    websocketonmessage(socketMsg) {
      // 数据接收
      const redata = JSON.parse(socketMsg.data)
      if (redata.msgType === 'dorm_user_scan_user_qr') {
        this.currentStep = 1
        this.userId = redata.msgContent
        this.distributionLogFun()
      }
      // 接受传入扫码信息
      // 赋值
      // 触发查询
      // if (redata.type === 6) {
      //   console.log('接收到新的信息')
      //   this.drawerData = redata
      // }
      console.log('接收的数据', redata)
    },
    websocketsend(Data) {
      // 数据发送
      this.websock.send(Data)
    },
    websocketclose(e) {
      // 关闭
      console.log('断开连接', e)
      this.websocketonerror()
      this.conStatus = false
    },
    destroyed() {
      // 离开路由之后断开websocket连接
      this.websock.close()
      this.conStatus = false
      this.currentRetry = 0
    }
  }
}
</script>
